package ru.rchervot.sanasar.client.place;

import ru.rchervot.sanasar.client.model.FactoryQueryCandidates;
import ru.rchervot.sanasar.client.rpc.RPCServiceAsync;
import ru.rchervot.sanasar.client.view.FactoryModuleCandidates;
import ru.rchervot.sanasar.client.view.RootPresenter;

import com.google.gwt.event.shared.HandlerManager;
import com.google.inject.Inject;

public class FactoryPlaceCandidates implements FactoryPlace {
	
	private final HandlerManager eventBus;
	private final RPCServiceAsync service;
	private final FactoryQueryCandidates factoryQuery;
	private final FactoryModuleCandidates factoryModule;
	private final RootPresenter rootPresenter;
	
	@Inject
	public FactoryPlaceCandidates(HandlerManager eventBus,
			RPCServiceAsync service, FactoryQueryCandidates factoryQuery,
			RootPresenter rootPresenter, FactoryModuleCandidates factoryModule) {
		this.eventBus = eventBus;
		this.service = service;
		this.factoryQuery = factoryQuery;
		this.rootPresenter = rootPresenter;
		this.factoryModule = factoryModule;
	}
	
	@Override
	public Place buildPlace(HistoryTokenObject hto) {
		if (hto.getPlaceName().equalsIgnoreCase(PlaceSearchCandidates.getPlaceName())) {
			return getPlaceSearch();
		} else if (hto.getPlaceName().equalsIgnoreCase(PlaceHistoryCandidates.getPlaceName())) {
			return getPlaceHistory();
		}
		
		return null;
	}
	
	private PlaceSearchCandidates placeSearch;
	private PlaceSearchCandidates getPlaceSearch() {
		if (placeSearch == null) {
			placeSearch = new PlaceSearchCandidates(
					eventBus, service, factoryQuery, rootPresenter, factoryModule);
		}
		
		currentPlace = placeSearch;
		
		return placeSearch;
	}

	
	private PlaceHistoryCandidates placeHistory;
	private PlaceHistoryCandidates getPlaceHistory() {
		if (placeHistory == null) {
			placeHistory = new PlaceHistoryCandidates(eventBus, service, 
					rootPresenter, factoryModule);
		}
		
		currentPlace = placeHistory;
		
		return placeHistory;
	}
	
	private Place currentPlace;
	@Override
	public Place getCurrentPlace() {
		if (currentPlace != null) {
			return currentPlace;			
		} else {
			return getPlaceSearch();
		}
	}
	
}


